<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :span="6">
        <div class="stat-card blue">
          <div class="stat-title">总泊位数</div>
          <div class="stat-value">{{ total }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card purple">
          <div class="stat-title">普通泊位</div>
          <div class="stat-value">{{ getSpotTypeCount('1') }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card orange">
          <div class="stat-title">充电泊位</div>
          <div class="stat-value">{{ getSpotTypeCount('2') }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card green">
          <div class="stat-title">空闲泊位</div>
          <div class="stat-value">{{ getFreeSpotCount() }}</div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="泊位编号" prop="spotCode">
          <el-input v-model="queryParams.spotCode" placeholder="请输入泊位编号" clearable size="small" />
        </el-form-item>
        <el-form-item label="泊位类型" prop="spotType">
          <el-select v-model="queryParams.spotType" placeholder="请选择泊位类型" clearable size="small">
            <el-option label="普通" value="1" />
            <el-option label="充电" value="2" />
            <el-option label="无障碍" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增泊位</el-button>
    </div>

    <!-- 表格部分 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="spotList" stripe>
        <el-table-column label="泊位编号" align="center" prop="spotCode" />
        <el-table-column label="泊位类型" align="center" prop="spotType">
          <template slot-scope="scope">
            <span>{{ getTypeLabel(scope.row.spotType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属停车场" align="center">
          <template slot-scope="scope">
            <span>{{ getParkingLotName(scope.row.lotId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用状态" align="center" prop="isOccupied">
          <template slot-scope="scope">
            <span>{{ getOccupiedLabel(scope.row.isOccupied) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加表单对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="泊位编号" prop="spotCode">
          <el-input v-model="form.spotCode" placeholder="请输入泊位编号" />
        </el-form-item>
        <el-form-item label="所属停车场" prop="lotId">
          <el-select v-model="form.lotId" placeholder="请选择所属停车场">
            <el-option
              v-for="lot in parkingLotMap"
              :key="lot.lotId"
              :label="lot.lotName || lot.name"
              :value="lot.lotId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="泊位类型" prop="spotType">
          <el-select v-model="form.spotType" placeholder="请选择泊位类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSpot, getSpot, delSpot, addSpot, updateSpot, getParkingStatus } from '@/api/spot/sprj';
import { parkingApi } from '@/api/parking';
import { Message } from 'element-ui';

export default {
  name: "ParkingSpotList",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      spotList: [],
      typeOptions: [
        { dictLabel: '普通', dictValue: '1' },
        { dictLabel: '充电', dictValue: '2' },
        { dictLabel: '无障碍', dictValue: '3' }
      ],
      occupiedOptions: [
        { dictLabel: '空闲', dictValue: '0' },
        { dictLabel: '占用', dictValue: '1' }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spotCode: undefined,
        spotType: undefined
      },
      parkingStatusList: [],
      parkingLotMap: {},
      // 新增表单对话框
      dialog: {
        title: '',
        visible: false
      },
      // 表单数据
      form: {
        spotId: undefined,
        spotCode: '',
        lotId: undefined,
        spotType: '1',
        isOccupied: '0'
      },
      // 表单校验规则
      rules: {
        spotCode: [
          { required: true, message: '请输入泊位编号', trigger: 'blur' }
        ],
        lotId: [
          { required: true, message: '请选择所属停车场', trigger: 'change' }
        ],
        spotType: [
          { required: true, message: '请选择泊位类型', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listSpot(this.queryParams).then(response => {
        this.spotList = response.rows;
        this.total = response.total;
        // 获取每个泊位对应的停车场信息
        this.spotList.forEach(spot => {
          this.loadParkingLotInfo(spot.lotId);
        });
        this.loading = false;
      });
    },

    // 新增方法：加载单个停车场信息
    loadParkingLotInfo(lotId) {
      // 如果已经加载过该停车场信息，则不重复加载
      if (this.parkingLotMap[lotId]) return;

      parkingApi.getParkingLotInfo(lotId).then(response => {
        if (response.data) {
          this.$set(this.parkingLotMap, lotId, response.data);
        }
      }).catch(error => {
        console.error('获取停车场信息失败:', error);
      });
    },

    getParkingStatusList() {
      getParkingStatus().then(response => {
        this.parkingStatusList = response.rows;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.dialog.title = "新增泊位";
      this.dialog.visible = true;
      this.form = {
        spotCode: '',
        lotId: undefined,
        spotType: '1',
        isOccupied: '0'
      };
    },
    handleUpdate(row) {
      this.dialog.title = "修改泊位";
      this.dialog.visible = true;
      this.form = {...row};  // 复制行数据到表单
    },
    handleDelete(row) {
      this.$confirm('是否确认删除泊位编号为"' + row.spotCode + '"的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delSpot(row.spotId);
      }).then(() => {
        this.getList();
        Message.success("删除成功");
      }).catch(() => {
        Message.info("已取消删除");
      });
    },
    getTypeLabel(value) {
      const option = this.typeOptions.find(opt => opt.dictValue === value);
      return option ? option.dictLabel : '';
    },
    getOccupiedLabel(value) {
      const option = this.occupiedOptions.find(opt => opt.dictValue === value);
      return option ? option.dictLabel : '';
    },
    getParkingLotName(lotId) {
      const parkingLot = this.parkingLotMap[lotId];
      if (!parkingLot) {
        console.log(`未找到ID为${lotId}的停车场信息`);
        return '未知停车场';
      }
      return parkingLot.lotName || parkingLot.name || '未知停车场';
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.spotId) {
            // 修改
            updateSpot(this.form).then(response => {
              Message.success("修改成功");
              this.dialog.visible = false;
              this.getList();
            });
          } else {
            // 新增
            addSpot(this.form).then(response => {
              Message.success("新增成功");
              this.dialog.visible = false;
              this.getList();
            }).catch(error => {
              Message.error("新增失败：" + error.message);
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.dialog.visible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        spotCode: '',
        lotId: undefined,
        spotType: '1',
        isOccupied: '0'
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    // 新增统计方法
    getSpotTypeCount(type) {
      return this.spotList.filter(spot => spot.spotType === type).length;
    },
    getFreeSpotCount() {
      return this.spotList.filter(spot => spot.isOccupied === '0').length;
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.dashboard-cards {
  margin-bottom: 20px;
  
  .stat-card {
    padding: 20px;
    border-radius: 10px;
    color: white;
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .stat-title {
      font-size: 16px;
      opacity: 0.9;
    }
    
    .stat-value {
      font-size: 32px;
      font-weight: bold;
    }
    
    &.blue {
      background: linear-gradient(135deg, #1890ff 0%, #36a6ff 100%);
    }
    
    &.purple {
      background: linear-gradient(135deg, #722ed1 0%, #8e44ad 100%);
    }
    
    &.orange {
      background: linear-gradient(135deg, #ff6b00 0%, #ff8c3f 100%);
    }
    
    &.green {
      background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
    }
  }
}

.search-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}

.action-container {
  margin-bottom: 20px;
}

.table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
  
  .el-table {
    margin: 10px 0;
  }
}

.el-button {
  border-radius: 4px;
  
  &--primary {
    background: #1890ff;
    border-color: #1890ff;
    
    &:hover, &:focus {
      background: #40a9ff;
      border-color: #40a9ff;
    }
  }
}

.el-input, .el-select {
  .el-input__inner {
    border-radius: 4px;
  }
}

.pagination-container {
  padding: 15px 0;
  text-align: right;
}

// 对话框样式优化
.el-dialog {
  border-radius: 8px;
  
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .el-dialog__body {
    padding: 30px 20px;
  }
  
  .el-dialog__footer {
    padding: 20px;
    border-top: 1px solid #f0f0f0;
  }
}

// 表单项样式优化
.el-form-item {
  margin-bottom: 22px;
  
  &__label {
    font-weight: 500;
  }
}
</style> 